using System.Net.Http.Headers;
using Microsoft.Extensions.Options;
using OpenAIProxy;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();
builder.Services.Configure<OpenAIConfig>(builder.Configuration.GetSection("OpenAIConfig"));
builder.Services.Configure<FileStorageConfig>(builder.Configuration.GetSection("FileStorage"));
builder.Services.AddSingleton<ITokenCounter, TokenCounter>();
builder.Services.AddTransient<ITokenAccumulator, TokenAccumulator>();
builder.Services.AddSingleton<TokenAccumulator>(provider => 
    new TokenAccumulator(provider.GetRequiredService<ITokenCounter>()));
builder.Services.AddSingleton<IFileStorage, FileStorageService>();
builder.Services.AddSingleton<IStorageService, PersistentStorage>();
builder.Services.AddSingleton<ConfigManager>();
builder.Services.AddSingleton<OpenAIHttpClientFactory>();
builder.Services.AddSingleton<OpenAIServiceSelector>();
builder.Services.Configure<ProxySettings>(builder.Configuration.GetSection("ProxySettings"));

builder.Services.AddHttpClient("OpenAI", (prov, client) => 
{
    var config = prov.GetRequiredService<IOptions<OpenAIConfig>>().Value;
    client.BaseAddress = new Uri(config.Endpoint);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", config.ApiKey);
});
builder.Services.AddStreamingCapture();
builder.Services.AddControllers();

var app = builder.Build();
app.UseMiddleware<StreamingCaptureMiddleware>();
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");
app.UseRouting();
app.MapControllers();
app.UseStreamingCapture();
app.MapControllers();
app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class ProxySettings
{
    public ProviderSelectionStrategy ProviderSelectionStrategy { get; set; }
}